import React, { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { isPropertyAccessOrQualifiedName } from 'typescript';
//将图片文件读取成base64格式的地址
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('你只能上传 JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('你上传的图片要小于 1MB!');
  }
  return isJpgOrPng && isLt2M;
};

const MyUpload: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    //正在上传
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    //上传成功
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      message.success('上传成功')
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
    //上传出错
    if (info.file.status==='error'){
        setLoading(false)
        message.error('上传出错')
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <Upload
      name="img"
      method='post'
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="/api/upload/uploadImg"
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
    </Upload>
  );
};

export default MyUpload;